<template>
  <div>
    <div class="condition">
      <div class="condition-text" v-for="(item,index) in conditions" :key="index" @click="onChange(item,index)"
           v-bind:class="{back:index==isActive,change_back:index!=isLine}">
        <span>{{ item }}</span>
      </div>
      <Icon type="ios-refresh" size="25" style="float:right; cursor: pointer; margin-left: 10px;" @click.native="refresh"/>
      <Icon type="ios-qr-scanner" size="25" title="全屏" style="float:right; cursor: pointer; margin-left: 10px;"
            @click.native="fullScreen"/>
    </div>
    <div class="grid-type"><span>缺陷类型：</span>
      <Select class="form-width" multiple clearable v-model="defectTypeId" @on-change='changeDefectType' style="width:200px" :max-tag-count="1">
        <Option
                :key="item.id"
                :value="item.id"
                v-for="item in defectTypeList"
              >{{ item.defectName }}</Option>
      </Select>
    </div>
    <div class="line-main"
         id="chartLineGrid"
         ref="chartDom" style="margin-top: 30px"></div>
  </div>
</template>

<script>
import echarts from 'echarts';
import tdTheme from './theme.json';
import {statApi} from '@/api/stat';
import { taskDefectTypeApi } from '@/api/task-defect-type';
import {on, off} from '@/lib/util';

echarts.registerTheme('tdTheme', tdTheme);
export default {
  data() {
    return {
      isActive: false,
      isLine: false,
      defectTypeList: [],
      defectTypeId: [],
      lineData: [],
      timeTypes: 1,
      chartDom: null,
      conditions: [
        '近7天', '近30天'
      ]
    }
  },
  props: {
    value: Array,
    text: String,
    subtext: String
  },
  watch: {
    lineData: {
      handler(newVal, oldVal) {
        if (this.chartDom) {
          if (newVal) {
            this.setOption(newVal);
          } else {
            this.setOption(oldVal);
          }
        } else {
          this.initChart();
        }
      }, deep: true
    }
  },
  mounted() {
      taskDefectTypeApi.getTaskDefectType()
        .then(res => {
          this.defectTypeList = res.data;
          if (res.data && res.data.length > 0) {
            this.defectTypeId = this.defectTypeList[0].id;
          }
        }).then(() => {
          this.getElectricTrends(this.timeTypes);
        })
  },
  methods: {
    onChange(item, index) {
      this.isActive = index;
      this.isLine = index;
      let timeType = 0;
      switch (index) {
        case 0:
          timeType = 1;
          break;
        case 1:
          timeType = 2;
          break;
        case 2:
          timeType = 3;
          break;
      }
      this.timeTypes = timeType;
      this.getElectricTrends(timeType)
    },
    async getElectricTrends(timeType) {
      try {
        let defectTypeIdList = []
        if (this.defectTypeId.length === undefined)
          defectTypeIdList.push(this.defectTypeId)
        else
          defectTypeIdList = this.defectTypeId
        let params = {
          dateType: timeType,
          defectTypeIdList: defectTypeIdList
        }
        statApi.countElectricCoreByDefectType(params).then(res => {
          if (res.code === 1) {
            this.lineData = res.data;
          }
        })
      } catch (e) {
        console.error(e);
      } finally {
      }
    },
    async initDefectType() {
      let that = this;
      let result = await taskDefectTypeApi.getTaskDefectType();
      that.defectTypeList = result.data;
      if (result.data && result.data.length > 0) {
        that.defectTypeId = that.defectTypeList[0].id;
      }
    },
    changeDefectType(value){
      this.getElectricTrends(this.timeTypes);
    },
    resize() {
      this.chartDom.resize();
    },
    setOption(value) {
      this.$nextTick(() => {
        let option = this.getOption(value);
        this.chartDom.setOption(option,true);
      })
    },
    initChart() {
      this.$nextTick(() => {
        let option = this.getOption();
        this.chartDom = echarts.init(this.$refs.chartDom, 'tdTheme');
        this.chartDom.setOption(option);
        on(window, 'resize', this.resize);
      });
    },
    getOption() {
        let xAxisData = this.lineData.xaxisData;
        let legend = this.lineData.legendList;
        let series = [];
        this.lineData.chartLineSerieList.forEach(item => {
            let obj = {
              name: item.name,
              type: 'line',
              // stack: 'x',
              showSymbol: false,
              data: item.data
            }
            series.push(obj);
        });
        let option = {
          grid: {
            left: '1%',
            right: '2%',
            top: '2%',
            bottom: '15%',
            containLabel: true
          },
          title: {
            text: this.text,
            subtext: this.subtext,
            x: 'center'
          },
          tooltip: {
            trigger: 'axis',
            // formatter: '{c}人',
            // position: ['30%', '90%'],
            show: true,
            position: 'top',
            backgroundColor: '#387DE1',
            textStyle: {
              fontSize: 18,
              color: '#fff'
            }
          },
          legend: {
            data: legend,
            orient: 'horizontal',
            icon: 'square',
            x: 'center',      //可设定图例在左、右、居中
            y: 'bottom'     //可设定图例在上、下、居中
          },
          xAxis: {
            // show: false,
            type: 'category',
            data: xAxisData,
            splitLine: {
              show: false
            }
          },
          yAxis: [
            {
              type: 'value'
            }
          ],
          series: series
        };
        return option;
    },
    refresh() {
      taskDefectTypeApi.getTaskDefectType()
        .then(res => {
          this.defectTypeList = res.data;
          // if (res.data && res.data.length > 0) {
          //   this.defectTypeId = this.defectTypeList[0].id;
          // }
        }).then(() => {
          this.getElectricTrends(this.timeTypes);
        })
    },
    fullScreen() {
      let domName = document.getElementById('chartLineGrid');
      // 全屏查看
      if (domName.requestFullScreen) { // HTML W3C 提议
        domName.requestFullScreen()
      } else if (domName.msRequestFullscreen) { // IE11
        domName.msRequestFullScreen()
      } else if (domName.webkitRequestFullScreen) { // Webkit
        domName.webkitRequestFullScreen()
      } else if (domName.mozRequestFullScreen) { // Firefox
        domName.mozRequestFullScreen()
      }
      // 退出全屏
      if (domName.requestFullScreen) {
        document.exitFullscreen()
      } else if (domName.msRequestFullScreen) {
        document.msExitFullscreen()
      } else if (domName.webkitRequestFullScreen) {
        document.webkitCancelFullScreen()
      } else if (domName.mozRequestFullScreen) {
        document.mozCancelFullScreen()
      }
    }
  }
};
</script>

<style lang="less" scoped>
.line-main {
  width: 100%;
  height: 360px;
  padding: 28px;
  background: #fff;
}
.grid-type{
    position: absolute;
    top: 60px;
    right: 20px;
    display: -webkit-inline-box;
    display: -ms-inline-flexbox;
    display: inline-flex;
    float: right;
    span{
      line-height: 30px;
    }
}
</style>
